﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;

namespace MultiSelectListBox
{
    public partial class MainPage : PhoneApplicationPage
    {
		private readonly ObservableCollection<string> testList;
        public MainPage()
        {
            InitializeComponent();
            testList = new ObservableCollection<string> { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen"};
			lstToTest.ItemsSource = testList;
        }

		private void SelectAllItemButton_Click(object sender, EventArgs e)
        {
            SelectAllItems(lstToTest);
        }

		private void ClearAllItemButton_Click(object sender, EventArgs e)
        {
            UnSelectAllItems(lstToTest);
        }

        private void SaveIconButton_Click(object sender, EventArgs e)
        {
            uint totalSelectionCount = 0;
            for (int i = 0; i < lstToTest.Items.Count; i++)
            {
                ListBoxItem item = (ListBoxItem)lstToTest.ItemContainerGenerator.ContainerFromIndex(i);
                if (item.IsSelected)
                    totalSelectionCount++;
            }
            MessageBox.Show("Total selected items are: " + totalSelectionCount.ToString());
        }

        /// <summary>
        /// Selects all Items in a listBox
        /// </summary>
        /// <param name="lst"></param>
        private void SelectAllItems(ListBox lst)
        {
            for (int i = 0; i < lst.Items.Count; i++)
            {
                ListBoxItem item = (ListBoxItem)lst.ItemContainerGenerator.ContainerFromIndex(i);
                if (!item.IsSelected)
                    item.IsSelected = true;
            }
        }

        /// <summary>
        /// unselect all Items in a listBox
        /// </summary>
        /// <param name="lst"></param>
        private void UnSelectAllItems(ListBox lst)
        {
            for (int i = 0; i < lst.Items.Count; i++)
            {
                ListBoxItem item = (ListBoxItem)lst.ItemContainerGenerator.ContainerFromIndex(i);
                if (item.IsSelected)
                    item.IsSelected = false;
            }
        }
    }
}
